﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Threading;
using PicToPdf.Helper;

namespace PicToPdf
{
    public partial class Form_Main : Form
    {
        public Form_Main()
        {
            InitializeComponent();
            //开启跨线程访问UI
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        static List<string> file = new List<string>();

        //读取
        private void btn_Read_Click(object sender, EventArgs e)
        {
            string path = txt_readPath.Text;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("目录不存在");
                return;
            }

            var di = new DirectoryInfo(path);//文件夹所在目录
            var fc = new FileComparer();
            FileInfo[] fileList = di.GetFiles();
            Array.Sort(fileList, fc);//按文件创建时间排正序

            file = fileList
               .Where(t => t.Name.Contains(".png") || t.Name.Contains(".jpg"))
               .Select(t => t.FullName)
               .ToList();
            //rich_text_content.Text = string.Join("\n", file);

            lab_fileNum.Text = "读取到文件数量：" + file.Count;
            txt_end.Text = file.Count.ToString();
        }

        //创建
        private void btn_create_Click(object sender, EventArgs e)
        {

            ThreadStart threadStart = new ThreadStart(ToPicHead);
            Thread thread = new Thread(threadStart);
            thread.Start();

            //MessageBox.Show("生成完成！");
        }

        public void ToPicHead()
        {
            int fileCount = file.Count;
            if (fileCount == 0)
            {
                MessageBox.Show("请先读取数据");
                return;
            }

            int chartNum = 0;
            if (!int.TryParse(txt_fileCount.Text, out chartNum))
            {
                MessageBox.Show("每个章节的文件数填写错误");
                return;
            }
            int start = 0;
            if (!int.TryParse(txt_begin.Text, out start) && start > 0)
            {
                MessageBox.Show("起始章节有误");
                return;
            }
            int end = 0;
            if (!int.TryParse(txt_end.Text, out end) && end <= fileCount)
            {
                MessageBox.Show("结尾章节有误");
                return;
            }

            if (end < start)
            {
                MessageBox.Show("起始数不能大于结束数");
                return;
            }

            string path = DateTime.Now.ToString("yyyyMMddHHmmss");
            Directory.CreateDirectory(path);
            //生成的文件个数
            int count = (end - start) % chartNum == 0 ? (end - start) / chartNum : (end - start) / chartNum + 1;
            DateTime startTime = DateTime.Now;

            string fileName = txt_newFileName.Text;
            if (string.IsNullOrEmpty(fileName?.Trim()))
            {
                fileName = "file";
            }
            for (int i = 0; i < count; i++)
            {
                var data = file.Skip(i * chartNum + start - 1).Take(chartNum).ToList();
                if (data != null && data.Count != 0)
                {
                    ToPic(path + $"/{fileName}_{i}.pdf", data);
                    rich_text_content.Text += "生成成功：" + $"{fileName}_{i}.pdf\n";
                }
            }
            DateTime endTime = DateTime.Now;

            rich_text_content.Text += "生成完成:\n" + "共花费：" + (endTime - startTime).TotalSeconds.ToString("f2") + "s";
        }


        public void ToPic(string fullPath, List<string> files)
        {
            Document document = new Document(PageSize.A4, 0f, 0f, 15f, 0f);
            PdfWriter.GetInstance(document, new FileStream(fullPath, FileMode.Create));
            document.Open();

            PdfPTable table = new PdfPTable(1);//列数
            table.TotalWidth = 560;
            table.LockedWidth = true;
            PdfPCell cell;

            foreach (var item in files)
            {
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);
                cell = new PdfPCell(image, true);
                table.AddCell(cell);
            }

            document.Add(table);
            document.Close();
        }

        //图片压缩
        private void btn_yasuo_Click(object sender, EventArgs e)
        {
            int yasuo_rate = 0;
            string path = txt_yasuo_path.Text;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("压缩后目录不存在！");
                return;
            }

            if (!int.TryParse(txt_yasuo_Rate.Text, out yasuo_rate) || yasuo_rate <= 0 || yasuo_rate > 100)
            {
                MessageBox.Show("压缩率格式错误");
                return;
            }
            rich_text_content.Text = "开始压缩图片\n";

            ThreadStart threadStart = new ThreadStart(() => YaSuoAll(path, yasuo_rate));
            Thread thread = new Thread(threadStart);
            thread.Start();
        }

        public void YaSuoAll(string yasuo_path, int yasuo_rate)
        {
            int index = 1;
            foreach (var item in file)
            {
                rich_text_content.Text += index.ToString() + "\n";
                PicHelper.GetPicThumbnail(item, yasuo_path + "/" + Path.GetFileName(item), yasuo_rate);
                index++;
            }
            rich_text_content.Text += "压缩完成！\n";
        }
    }

    public class FileComparer : IComparer
    {
        /// <summary>
        /// 文件排序
        /// </summary>
        /// <param name="o1"></param>
        /// <param name="o2"></param>
        /// <returns></returns>
        int IComparer.Compare(object o1, object o2)
        {
            FileInfo fi1 = o1 as FileInfo;
            FileInfo fi2 = o2 as FileInfo;
            return fi1.CreationTime.CompareTo(fi2.CreationTime);
        }
    }
}
